package com.example.iqiyitest.activity;

import android.R.bool;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.iqiyitest.R;
import com.example.iqiyitest.TestView;
import com.example.iqiyitest.base.Constants;
import com.example.iqiyitest.hztvpaysdk.PushMessage;
import com.example.iqiyitest.info.MovieInfo;
import com.example.iqiyitest.view.TestViewForMovie;
import com.google.gson.Gson;
import com.iqiyi.movieksdk.sdk.exported.CodecType;
import com.iqiyi.movieksdk.sdk.exported.OnPlayStateChangeListener;
import com.iqiyi.movieksdk.sdk.exported.PlayerContract;

import org.apache.commons.net.nntp.NewGroupsOrNewsQuery;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;

public class PlayMovieActivity extends Activity implements OnPlayStateChangeListener {

	private static final String TAG = "PlayerActivity";
	private TestViewForMovie testView;
	private PlayerContract.Presenter playController;
	private ProgressBar progressBar;
	private long position;
	public String movie_flag = "1";
	LinearLayout play_status_ly;
	ImageView play_status_img;
	SeekBar play_status_seekbar;
	TextView play_status_tx;
	boolean play_status = true, show_status = true;
	private Gson mGson = new Gson();
	MovieInfo movieInfo2;
	long seektime = 0, seekbacktime = 0;
	Thread t;

	protected int progress = 0;// 当前的时间
	protected int totaltime = 0;// 总共的时间
	public double ratio = 1;
	public final boolean FORWARD_BACKWARD_MODE = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		long qipuId = getIntent().getLongExtra("qipuId", 0l);
		int playType = getIntent().getIntExtra("playType", 0);
		testView = new TestViewForMovie(this, qipuId, playType, this);// 0，大播放
																		// 1，new
																		// player
		progressBar = (ProgressBar) testView.findViewById(R.id.progress);
		play_status_ly = (LinearLayout) testView.findViewById(R.id.play_status_ly);
		play_status_img = (ImageView) testView.findViewById(R.id.play_status_img);
		play_status_seekbar = (SeekBar) testView.findViewById(R.id.play_status_seekbar);
		play_status_tx = (TextView) testView.findViewById(R.id.play_status_tx);
		movie_flag = Constants.getMovie_flag();
		setContentView(testView);
		testView.onCreate();
		playController = testView.getPlayImp();
		playController.doSetCodecType(CodecType.SYSTEM);
		playController.doSetPlayerSize(false);
		playController.doStart();
		// if(movie_flag.equals("2")) {
		// playController.doStart();
		// }
		new Thread() {
			public void run() {
				try {
					while (true) {
						Message m = new Message();
						m.what = 1;
						zuixinHandler.sendMessage(m);
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	private Handler zuixinHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (show_status) {
					getMovieInfoforMovie();
				}
				break;
			case 2:
				// play_status_ly.setVisibility(View.GONE);
				stopShow();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	public SeekBar getProgressBar() {
		return play_status_seekbar;
	}

	public void beginShow() {
		show_status = true;
	}

	public void stopShow() {
		show_status = false;
	}

	public void dismissProbar() {
		new Thread() {
			public void run() {
				try {
					Thread.sleep(10000);
					Message m = new Message();
					m.what = 2;
					zuixinHandler.sendMessage(m);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// playController.notifyAll();
		playController.doStop();
		testView.onDestory();
	}

	public void changeSize(View v) {
		playController.doSetPlayerSize(new Random().nextInt(1000), new Random().nextInt(1000));
	}

	public void play() {
		playController.doStart();
	}

	public void pause() {
		playController.doPlayOrPause(false);
		play_status = false;

	}

	public void resume() {
		playController.doPlayOrPause(true);
		play_status = true;
	}

	public void seek() {
		playController.doSeek(seektime);
	}

	public void seekback() {
		playController.doSeek(-seektime);
	}

	public void stop(View v) {
		playController.doStop();
	}

	public void getMovieInfoforMovie() {
		String movieInfo = getMovieInfo();
		Log.d(TAG, movieInfo);
		movieInfo2 = mGson.fromJson(movieInfo, MovieInfo.class);
		if (movieInfo2.getMoviePosition() == -1 || movieInfo2.getMoviePosition() == 0) {
			// play_status_seekbar.setProgress(0);
			// play_status_tx.setText("0/0");
		} else {
			long movieposition = Long.valueOf(movieInfo2.getMoviePosition());
			long movietotal = Long.valueOf(movieInfo2.getMovieTotalTime());
			play_status_seekbar.setMax(movieInfo2.getMovieTotalTime());
			play_status_seekbar.setProgress(movieInfo2.getMoviePosition());
			progress = movieInfo2.getMoviePosition();
			totaltime = movieInfo2.getMovieTotalTime();
			// play_status_seekbar.setProgress((movieInfo2.getMoviePosition() /
			// movieInfo2.getMovieTotalTime()) * 100);
			play_status_tx.setText(timeParse(movieposition) + "/" + timeParse(movietotal));
		}
	}

	public static String timeParse(long duration) {
		String time = "";
		long minute = duration / 60000;
		long seconds = duration % 60000;
		long second = Math.round((float) seconds / 1000);
		if (minute < 10) {
			time += "0";
		}
		time += minute + ":";
		if (second < 10) {
			time += "0";
		}
		time += second;
		return time;
	}

	public String getMovieInfo() {

		return playController.doGetMovieInfo();
	}

	@Override
	public void showPlayEnd() {
		// Toast.makeText(this, "showPlayEnd", Toast.LENGTH_SHORT).show();
		playController.doStop();
		this.finish();
	}

	@Override
	public void showPlayBegin() {
		// Toast.makeText(this, "showPlayBegin", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void showLoading() {
		// Toast.makeText(this, "showLoading", Toast.LENGTH_SHORT).show();
		beginShow();
		progressBar.setVisibility(View.VISIBLE);
		play_status_ly.setVisibility(View.VISIBLE);

	}

	@Override
	public void showLoadingComplete() {
		// Toast.makeText(this, "showLoadingComplete",
		// Toast.LENGTH_SHORT).show();
		dismissProbar();
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void showPause() {
		// Toast.makeText(this, "showPause", Toast.LENGTH_SHORT).show();
		beginShow();
		play_status_img.setBackgroundResource(R.drawable.play);
		progressBar.setVisibility(View.VISIBLE);
		play_status_ly.setVisibility(View.VISIBLE);
	}

	@Override
	public void showPlaying() {
		// Toast.makeText(this, "showPlaying", Toast.LENGTH_SHORT).show();
		play_status_img.setBackgroundResource(R.drawable.pause);
		dismissProbar();
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void showSeek() {
		beginShow();
		// Toast.makeText(this, "seek", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void showPlayError(int code, String error) {
		Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void showValidateFailed(int i, String s) {
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (event.getKeyCode()) {
			case KeyEvent.KEYCODE_DPAD_UP:
				break;
			case KeyEvent.KEYCODE_DPAD_LEFT:
				beginShow();
				seekbacktime = seekbacktime + 10 * 1000;
				fastControl(-Integer.valueOf(String.valueOf(seekbacktime / 10000)));
				break;
			case KeyEvent.KEYCODE_DPAD_RIGHT:
				beginShow();
				seektime = seektime + 10 * 1000;
				fastControl(Integer.valueOf(String.valueOf(seektime / 10000)));
				break;
			case KeyEvent.KEYCODE_DPAD_DOWN:
				// sendIRKey(KeyEvent.KEYCODE_VOLUME_DOWN);
				break;
			case KeyEvent.KEYCODE_ENTER:
			case KeyEvent.KEYCODE_DPAD_CENTER:
				// sendIRKey(KeyEvent.KEYCODE_VOLUME_DOWN);
				Log.e(TAG, "KEYCODE_DPAD_CENTERKEYCODE_DPAD_CENTERKEYCODE_DPAD_CENTERKEYCODE_DPAD_CENTER");
				if (play_status) {
					pause();
				} else {
					resume();
				}
				break;
			default:
				break;
			}
		}
		if (event.getAction() == KeyEvent.ACTION_UP) {
			switch (event.getKeyCode()) {
			case KeyEvent.KEYCODE_DPAD_LEFT:
				seekback();
				break;
			case KeyEvent.KEYCODE_DPAD_RIGHT:
				seek();
				break;
			default:
				break;
			}
		}
		return super.dispatchKeyEvent(event);

	}

	public void fastControl(int i) {
		Message msg = new Message();
		msg.what = 1;
		msg.arg1 = i;
		fastBarHandler.sendMessage(msg);
		fastBarHandler.removeMessages(2);
		fastBarHandler.sendEmptyMessageDelayed(2, 500);
	}

	/**
	 * 进度条监听器
	 */
	protected Handler fastBarHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			SeekBar progressBar = getProgressBar();
			if (msg.what == 1) {
				// if (ratio < 15) {
				// ratio += 0.1;
				// }
				// progress += (int) (6000) * msg.arg1;
				// // progress +=msg.arg1;
				// if (msg.arg1 > 0) {
				// progress = (progress > totaltime? totaltime : progress);
				// } else {
				// progress = (progress > 0 ? progress : 0);
				// }
				progress += msg.arg1;
				 if (msg.arg1 > 0) {
				 progress = (progress > totaltime? totaltime : progress);
				 } else {
				 progress = (progress > 0 ? progress : 0);
				 }
				progressBar.setProgress(progress);

			} else if (msg.what == 2) {
				ratio = 1;
				// progressBar.setProgress(progress);
				progressBar.setProgress(progress);
			}
		}
	};

	public static String formatMillisecond(long millisecond) {
		long time = millisecond / 1000;
		if (time <= 0) {
			return "00:00:00";
		}

		return String.format(Locale.getDefault(), "%02d:%02d:%02d", time / 60 / 60, time / 60 % 60, time % 60);
	}
}
